Skip to main content

600. Testing with Jest

Unit Testing with Jest

Installation

npm i --save-dev @nestjs/testing

Run Test Commands

npm run test   # for unit tests
npm run test:cov # for test coverage
npm run test:e2e # for e2e tests

npm run test:watch -- coffees.service # run specific sile in watch mode
describe('findOne', () => {
describe('when user exists', () => {
it('should return user', () => {
expect(appController.findOne(1)).toEqual({
id: 1,
name: 'user1',
});
});
});

describe('when user does not exist', () => {
it('should return null', () => {
expect(appController.findOne(2)).toBeNull();
});
})
})
  • close app after running e2e tests
    • nest will give you warning about Jest did not exit one second after the test run has completed
    • to fix this
      • add an afterAll jest method to close the app
      • change beforeEach to beforeAll, we don't want to recreate the whole app in e2e tests for each test
beforeAll(async () => {
await app.init();
})

//tests...

afterAll(async () => {
await app.close();
})
  • npm has a pre-built in option, to make commands run before and after a certain command is executed
    • for example: we can create a test db before running a test and remote the test db after running the test, just using npm
    • to do this, add pre[npmcommand], or/and post[npmcommand]
"pretest:e2e": "docker compose up -d test-db",
"test:e2e": "jest ...",
"posttest:e2e": "docker compose stop test-dp && docker compose rm -f test-db"

HTTP Testing with Supertest

  it(`/GET cats`, () => {
return request(app.getHttpServer())
.get('/cats')
.expect(200)
.expect({
data: catsService.findAll(),
});
});